package com.xcc.skinlibrary;

import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Looper;

import java.lang.reflect.Method;

import static com.xcc.skinlibrary.SkinManager.pluginApkPackageName;

/**
 * Created by 52463 on 2018/6/29.
 */

public class LoadPlugin extends Thread {
    public LoadPlugin(Context context, String pluginApkPath) {
        this.context = context;
        this.pluginApkPath = pluginApkPath;
    }

    private Context context;
    private String pluginApkPath;
    private OnLoadPluginListener onLoadPluginListener;

    public LoadPlugin setOnLoadPluginListener(OnLoadPluginListener onLoadPluginListener) {
        this.onLoadPluginListener = onLoadPluginListener;
        return this;
    }

    public void run() {
        ResourcesManager resourcesManager = null;
        try {
            AssetManager assetManager = AssetManager.class.newInstance();
            Method addAssetPath = assetManager.getClass().getMethod("addAssetPath", String.class);
            addAssetPath.invoke(assetManager, pluginApkPath);
            Resources curAppRes = context.getResources();
            Resources resources = new Resources(assetManager, curAppRes.getDisplayMetrics(), curAppRes.getConfiguration());
            resourcesManager = new ResourcesManager(resources, pluginApkPackageName);
        } catch (Exception e) {
        }
        new Handler(Looper.getMainLooper()).post(new CallBack(resourcesManager));
    }

    public class CallBack implements Runnable {
        public CallBack(ResourcesManager resourcesManager) {
            this.resourcesManager = resourcesManager;
        }

        private ResourcesManager resourcesManager;

        public void run() {
            if (onLoadPluginListener != null) {
                onLoadPluginListener.onLoad(resourcesManager);
            }
        }
    }
}
